package vis.core.service.mail.impl;

import vis.core.common.valid.Email;
import vis.core.common.valid.NotBlank;
import vis.core.common.valid.base.Valid;
import vis.core.domain.sys.ServiceException;
import vis.core.service.mail.EmailService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class EmailServiceImpl implements EmailService {
    @Value("${spring.mail.username}")
    private String from;

    @Resource
    private JavaMailSender mailSender;


    @Valid
    @Override
    public boolean send(@Email String from, @Email String to, @NotBlank String title, @NotBlank String content) {
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(to);
        message.setSubject(title);
        message.setText(content);
        try {
            mailSender.send(message);
        } catch (Exception e) {
            if (e.getMessage().contains("User not found")) {
                throw new ServiceException("邮箱不存在");
            }
            return false;
        }
        return true;
    }

    @Override
    public boolean send(@Email String to, @NotBlank String title, @NotBlank String content) {
        return send(from, to, title, content);
    }


}
